<template>
  <div class="backup-management">
    <div class="page-header">
      <h2>数据备份与恢复</h2>
      <p>管理系统数据库备份与恢复功能</p>
    </div>

    <!-- 备份配置标签页 -->
    <div class="backup-tabs">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="备份操作" name="backup">
          <!-- 操作区域 -->
          <div class="operation-section">
            <el-row :gutter="20">
        <!-- 数据备份区域 -->
        <el-col :span="12">
          <el-card class="operation-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <i class="el-icon-upload"></i>
                <span>数据备份</span>
              </div>
            </template>

            <el-form :model="backupForm" :rules="backupRules" ref="backupFormRef" label-width="100px">
              <el-form-item label="备份名称" prop="backupName">
                <el-input v-model="backupForm.backupName" placeholder="请输入备份名称"></el-input>
              </el-form-item>

              <el-form-item label="备份类型" prop="backupType">
                <el-select v-model="backupForm.backupType" placeholder="请选择备份类型" style="width: 100%">
                  <el-option label="全量备份" value="全量"></el-option>
                  <el-option label="增量备份" value="增量"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="performBackup" :loading="backupLoading">
                  <i class="el-icon-download"></i>
                  执行备份
                </el-button>
                <el-button @click="resetBackupForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- 数据恢复区域 -->
        <el-col :span="12">
          <el-card class="operation-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <i class="el-icon-refresh"></i>
                <span>数据恢复</span>
              </div>
            </template>

            <el-tabs v-model="restoreTab" type="border-card">
              <el-tab-pane label="上传文件恢复" name="upload">
                <el-upload
                  ref="uploadRef"
                  :action="''"
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  :limit="1"
                  accept=".sql"
                  drag
                >
                  <i class="el-icon-upload"></i>
                  <div class="el-upload__text">将备份文件拖到此处，或<em>点击上传</em></div>
                  <template #tip>
                    <div class="el-upload__tip">
                      只能上传.sql格式的备份文件，且不超过100MB
                    </div>
                  </template>
                </el-upload>

                <div class="restore-actions" style="margin-top: 20px;">
                  <el-button
                    type="danger"
                    @click="restoreFromUpload"
                    :disabled="!selectedFile"
                    :loading="restoreLoading"
                  >
                    <i class="el-icon-refresh-left"></i>
                    开始恢复
                  </el-button>
                  <el-button @click="clearUploadFile">清除文件</el-button>
                </div>
              </el-tab-pane>

              <el-tab-pane label="历史备份恢复" name="history">
                <el-select
                  v-model="selectedBackupId"
                  placeholder="请选择要恢复的备份记录"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="backup in recentBackups"
                    :key="backup.id"
                    :label="`${backup.backupName} - ${backup.backupType} - ${formatDateTime(backup.backupAt)}`"
                    :value="backup.id"
                  >
                    <span style="float: left">{{ backup.backupName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ formatDateTime(backup.backupAt) }}
                    </span>
                  </el-option>
                </el-select>

                <div class="restore-actions" style="margin-top: 20px;">
                  <el-button
                    type="danger"
                    @click="restoreFromHistory"
                    :disabled="!selectedBackupId"
                    :loading="restoreLoading"
                  >
                    <i class="el-icon-refresh-left"></i>
                    恢复此备份
                  </el-button>
                  <el-button @click="refreshRecentBackups">刷新列表</el-button>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 统计信息区域 -->
    <div class="statistics-section" style="margin-top: 20px;">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <i class="el-icon-data-line"></i>
            <span>备份统计信息</span>
            <el-button type="text" @click="refreshStatistics" style="float: right;">
              <i class="el-icon-refresh"></i>
              刷新
            </el-button>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.totalBackups || 0 }}</div>
              <div class="stat-label">总备份数</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.fullBackups || 0 }}</div>
              <div class="stat-label">全量备份</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ statistics.incrementalBackups || 0 }}</div>
              <div class="stat-label">增量备份</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-value">{{ formatFileSize(statistics.totalSize || 0) }}</div>
              <div class="stat-label">总大小</div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 备份记录列表 -->
    <div class="backup-list-section" style="margin-top: 20px;">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <i class="el-icon-document"></i>
            <span>备份记录列表</span>
            <el-button type="text" @click="refreshBackupList" style="float: right;">
              <i class="el-icon-refresh"></i>
              刷新
            </el-button>
          </div>
        </template>

        <!-- 查询条件 -->
        <div class="search-form">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="备份名称">
              <el-input v-model="searchForm.backupName" placeholder="请输入备份名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="备份类型">
              <el-select v-model="searchForm.backupType" placeholder="请选择备份类型" clearable>
                <el-option label="全量备份" value="全量"></el-option>
                <el-option label="增量备份" value="增量"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备份时间">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchBackups">
                <i class="el-icon-search"></i>
                查询
              </el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 表格 -->
        <el-table
          :data="backupList"
          v-loading="tableLoading"
          stripe
          border
          style="width: 100%; margin-top: 20px;"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="backupName" label="备份名称" min-width="150"></el-table-column>
          <el-table-column prop="backupType" label="备份类型" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.backupType === '全量' ? 'success' : 'info'">
                {{ scope.row.backupType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="backupAt" label="备份时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.backupAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="operatorName" label="操作人" width="120"></el-table-column>
          <el-table-column prop="filePath" label="文件路径" min-width="200" show-overflow-tooltip></el-table-column>
          <el-table-column label="文件状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.fileExists" type="success">存在</el-tag>
              <el-tag v-else type="danger">不存在</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="mini"
                @click="downloadBackup(scope.row)"
                :disabled="!scope.row.fileExists"
              >
                <i class="el-icon-download"></i>
                下载
              </el-button>
              <el-button
                type="warning"
                size="mini"
                @click="validateBackup(scope.row)"
              >
                <i class="el-icon-check"></i>
                验证
              </el-button>
              <el-button
                type="danger"
                size="mini"
                @click="deleteBackup(scope.row)"
              >
                <i class="el-icon-delete"></i>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>

          <div style="margin-top: 20px;">
            <el-button
              type="danger"
              :disabled="selectedBackups.length === 0"
              @click="batchDeleteBackups"
            >
              <i class="el-icon-delete"></i>
              批量删除
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
        </el-tab-pane>

        <el-tab-pane label="自动备份设置" name="schedule">
          <div class="schedule-section">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <i class="el-icon-time"></i>
                  <span>自动备份配置</span>
                  <el-button type="primary" size="small" @click="handleSaveSchedule" :loading="scheduleSaveLoading">
                    <i class="el-icon-check"></i> 保存设置
                  </el-button>
                </div>
              </template>

              <el-form :model="scheduleForm" :rules="scheduleRules" ref="scheduleFormRef" label-width="120px">
                <el-form-item label="启用自动备份">
                  <el-switch v-model="scheduleForm.enabled" active-text="启用" inactive-text="停用"></el-switch>
                </el-form-item>

                <div v-show="scheduleForm.enabled">
                  <el-form-item label="备份频率" prop="frequency">
                    <el-select v-model="scheduleForm.frequency" placeholder="请选择备份频率" style="width: 100%">
                      <el-option label="每天" value="daily"></el-option>
                      <el-option label="每周" value="weekly"></el-option>
                      <el-option label="每月" value="monthly"></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item label="执行时间" prop="executeTime">
                    <el-time-picker
                      v-model="scheduleForm.executeTime"
                      placeholder="选择执行时间"
                      format="HH:mm"
                      value-format="HH:mm"
                      style="width: 100%">
                    </el-time-picker>
                  </el-form-item>

                  <el-form-item label="备份类型" prop="backupType">
                    <el-radio-group v-model="scheduleForm.backupType">
                      <el-radio label="全量">全量备份</el-radio>
                      <el-radio label="增量">增量备份</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="保留天数" prop="retentionDays">
                    <el-input-number v-model="scheduleForm.retentionDays" :min="1" :max="365" style="width: 100%"></el-input-number>
                    <div class="form-tip">超过指定天数的备份文件将被自动删除</div>
                  </el-form-item>

                  <el-form-item label="备份路径" prop="backupPath">
                    <el-input v-model="scheduleForm.backupPath" placeholder="请输入备份文件存储路径"></el-input>
                  </el-form-item>

                  <el-form-item label="压缩备份">
                    <el-switch v-model="scheduleForm.compress" active-text="启用" inactive-text="停用"></el-switch>
                  </el-form-item>

                  <el-form-item label="邮件通知">
                    <el-switch v-model="scheduleForm.emailNotification" active-text="启用" inactive-text="停用"></el-switch>
                  </el-form-item>

                  <el-form-item label="通知邮箱" v-show="scheduleForm.emailNotification">
                    <el-input v-model="scheduleForm.notificationEmail" placeholder="请输入接收通知的邮箱地址"></el-input>
                  </el-form-item>
                </div>
              </el-form>
            </el-card>

            <!-- 最近备份任务 -->
            <el-card shadow="hover" style="margin-top: 20px;">
              <template #header>
                <div class="card-header">
                  <i class="el-icon-date"></i>
                  <span>最近备份任务</span>
                  <el-button type="text" @click="refreshScheduleTasks" style="float: right;">
                    <i class="el-icon-refresh"></i>
                    刷新
                  </el-button>
                </div>
              </template>

              <el-table :data="scheduleTasks" v-loading="tasksLoading" stripe border>
                <el-table-column prop="taskName" label="任务名称" width="200"></el-table-column>
                <el-table-column prop="executeTime" label="执行时间" width="180">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.executeTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="backupType" label="备份类型" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.backupType === '全量' ? 'success' : 'info'">
                      {{ scope.row.backupType }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="getTaskStatusType(scope.row.status)">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="duration" label="耗时" width="100"></el-table-column>
                <el-table-column prop="fileSize" label="文件大小" width="120">
                  <template #default="scope">
                    {{ formatFileSize(scope.row.fileSize) }}
                  </template>
                </el-table-column>
                <el-table-column prop="errorMessage" label="错误信息" min-width="200" show-overflow-tooltip></el-table-column>
              </el-table>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="备份日志" name="logs">
          <div class="logs-section">
            <el-card shadow="hover">
              <template #header>
                <div class="card-header">
                  <i class="el-icon-document"></i>
                  <span>备份操作日志</span>
                  <div style="float: right;">
                    <el-button type="primary" size="small" @click="handleExportLogs">
                      <i class="el-icon-download"></i> 导出日志
                    </el-button>
                    <el-button type="danger" size="small" @click="handleClearLogs">
                      <i class="el-icon-delete"></i> 清空日志
                    </el-button>
                  </div>
                </div>
              </template>

              <!-- 日志筛选 -->
              <div class="log-filters">
                <el-form :inline="true" :model="logFilterForm" size="small">
                  <el-form-item label="操作类型">
                    <el-select v-model="logFilterForm.operationType" placeholder="请选择操作类型" clearable>
                      <el-option label="手动备份" value="manual_backup"></el-option>
                      <el-option label="自动备份" value="auto_backup"></el-option>
                      <el-option label="数据恢复" value="restore"></el-option>
                      <el-option label="文件删除" value="delete"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="操作状态">
                    <el-select v-model="logFilterForm.status" placeholder="请选择操作状态" clearable>
                      <el-option label="成功" value="success"></el-option>
                      <el-option label="失败" value="failed"></el-option>
                      <el-option label="进行中" value="running"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="操作人">
                    <el-input v-model="logFilterForm.operator" placeholder="请输入操作人" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="时间范围">
                    <el-date-picker
                      v-model="logDateRange"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="searchLogs">
                      <i class="el-icon-search"></i> 查询
                    </el-button>
                    <el-button @click="resetLogFilter">
                      <i class="el-icon-refresh"></i> 重置
                    </el-button>
                  </el-form-item>
                </el-form>
              </div>

              <!-- 日志表格 -->
              <el-table :data="backupLogs" v-loading="logsLoading" stripe border style="margin-top: 20px;">
                <el-table-column prop="id" label="日志ID" width="100"></el-table-column>
                <el-table-column prop="operationType" label="操作类型" width="120">
                  <template #default="scope">
                    <el-tag :type="getOperationTypeColor(scope.row.operationType)">
                      {{ getOperationTypeName(scope.row.operationType) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="操作描述" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column prop="operatorName" label="操作人" width="120"></el-table-column>
                <el-table-column prop="operateTime" label="操作时间" width="180">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.operateTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.status === 'success' ? 'success' : scope.row.status === 'failed' ? 'danger' : 'warning'">
                      {{ scope.row.status === 'success' ? '成功' : scope.row.status === 'failed' ? '失败' : '进行中' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="duration" label="耗时" width="100"></el-table-column>
                <el-table-column prop="ipAddress" label="IP地址" width="130"></el-table-column>
                <el-table-column prop="userAgent" label="用户代理" min-width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button type="text" size="small" @click="viewLogDetail(scope.row)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页 -->
              <div class="pagination-container">
                <el-pagination
                  @size-change="handleLogSizeChange"
                  @current-change="handleLogCurrentChange"
                  :current-page="logCurrentPage"
                  :page-sizes="[10, 20, 50, 100]"
                  :page-size="logPageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="logTotal">
                </el-pagination>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import {
  performBackup,
  restoreFromUpload,
  restoreFromBackupRecord,
  getBackupPage,
  getRecentBackups,
  deleteBackup,
  batchDeleteBackups,
  downloadBackupFile,
  validateBackupFile,
  getBackupStatistics,
  checkBackupFileExists
} from '@/api/backup'

export default {
  name: 'BackupManagement',
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'backup',

      // 备份表单数据
      backupForm: {
        backupName: '',
        backupType: ''
      },
      backupRules: {
        backupName: [
          { required: true, message: '请输入备份名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        backupType: [
          { required: true, message: '请选择备份类型', trigger: 'change' }
        ]
      },
      backupLoading: false,

      // 恢复相关数据
      restoreTab: 'upload',
      selectedFile: null,
      selectedBackupId: null,
      restoreLoading: false,

      // 统计信息
      statistics: {},

      // 查询表单
      searchForm: {
        backupName: '',
        backupType: ''
      },
      dateRange: [],

      // 表格数据
      backupList: [],
      recentBackups: [],
      selectedBackups: [],
      tableLoading: false,

      // 分页数据
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 自动备份设置
      scheduleForm: {
        enabled: false,
        frequency: 'daily',
        executeTime: '02:00',
        backupType: '全量',
        retentionDays: 30,
        backupPath: '',
        compress: true,
        emailNotification: false,
        notificationEmail: ''
      },
      scheduleRules: {
        frequency: [
          { required: true, message: '请选择备份频率', trigger: 'change' }
        ],
        executeTime: [
          { required: true, message: '请选择执行时间', trigger: 'change' }
        ],
        backupType: [
          { required: true, message: '请选择备份类型', trigger: 'change' }
        ],
        retentionDays: [
          { required: true, message: '请输入保留天数', trigger: 'blur' }
        ],
        backupPath: [
          { required: true, message: '请输入备份路径', trigger: 'blur' }
        ]
      },
      scheduleSaveLoading: false,
      scheduleTasks: [],
      tasksLoading: false,

      // 备份日志
      logFilterForm: {
        operationType: '',
        status: '',
        operator: ''
      },
      logDateRange: [],
      backupLogs: [],
      logsLoading: false,
      logCurrentPage: 1,
      logPageSize: 10,
      logTotal: 0
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getBackupStatistics()
      this.getRecentBackups()
      this.getBackupList()
    },

    // 执行备份
    performBackup() {
      this.$refs.backupFormRef.validate(async (valid) => {
        if (valid) {
          this.backupLoading = true
          try {
            const res = await performBackup(this.backupForm.backupName, this.backupForm.backupType)
            if (res.code === 200) {
              this.$message.success('备份成功')
              this.resetBackupForm()
              this.getBackupStatistics()
              this.getBackupList()
              this.getRecentBackups()
            } else {
              this.$message.error(res.message || '备份失败')
            }
          } catch (error) {
            this.$message.error('备份失败：' + (error.message || '未知错误'))
          } finally {
            this.backupLoading = false
          }
        }
      })
    },

    // 重置备份表单
    resetBackupForm() {
      this.$refs.backupFormRef.resetFields()
    },

    // 处理文件选择
    handleFileChange(file) {
      this.selectedFile = file.raw
    },

    // 清除上传文件
    clearUploadFile() {
      this.selectedFile = null
      this.$refs.uploadRef.clearFiles()
    },

    // 从上传文件恢复
    async restoreFromUpload() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择备份文件')
        return
      }

      this.$confirm('确定要从上传的文件恢复数据库吗？此操作不可逆！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.restoreLoading = true
        try {
          const res = await restoreFromUpload(this.selectedFile)
          if (res.code === 200) {
            this.$message.success('数据恢复成功')
            this.clearUploadFile()
          } else {
            this.$message.error(res.message || '恢复失败')
          }
        } catch (error) {
          this.$message.error('恢复失败：' + (error.message || '未知错误'))
        } finally {
          this.restoreLoading = false
        }
      }).catch(() => {
        this.$message.info('已取消恢复操作')
      })
    },

    // 从历史备份恢复
    async restoreFromHistory() {
      if (!this.selectedBackupId) {
        this.$message.warning('请先选择要恢复的备份记录')
        return
      }

      this.$confirm('确定要从选中的备份记录恢复数据库吗？此操作不可逆！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.restoreLoading = true
        try {
          const res = await restoreFromBackupRecord(this.selectedBackupId)
          if (res.code === 200) {
            this.$message.success('数据恢复成功')
            this.selectedBackupId = null
          } else {
            this.$message.error(res.message || '恢复失败')
          }
        } catch (error) {
          this.$message.error('恢复失败：' + (error.message || '未知错误'))
        } finally {
          this.restoreLoading = false
        }
      }).catch(() => {
        this.$message.info('已取消恢复操作')
      })
    },

    // 获取统计信息
    async getBackupStatistics() {
      try {
        const res = await getBackupStatistics()
        if (res.code === 200) {
          this.statistics = res.data
        }
      } catch (error) {
        console.error('获取统计信息失败：', error)
      }
    },

    // 获取最近备份记录
    async getRecentBackups() {
      try {
        const res = await getRecentBackups(20)
        if (res.code === 200) {
          this.recentBackups = res.data
        }
      } catch (error) {
        console.error('获取最近备份记录失败：', error)
      }
    },

    // 获取备份列表
    async getBackupList() {
      this.tableLoading = true
      try {
        const params = {
          ...this.searchForm,
          startTime: this.dateRange ? this.dateRange[0] : null,
          endTime: this.dateRange ? this.dateRange[1] : null
        }

        const res = await getBackupPage(this.currentPage, this.pageSize, params)
        if (res.code === 200) {
          this.backupList = res.data.records
          this.total = res.data.total

          // 检查文件是否存在
          for (let backup of this.backupList) {
            try {
              const existsRes = await checkBackupFileExists(backup.id)
              backup.fileExists = existsRes.data
            } catch (error) {
              backup.fileExists = false
            }
          }
        }
      } catch (error) {
        this.$message.error('获取备份列表失败：' + (error.message || '未知错误'))
      } finally {
        this.tableLoading = false
      }
    },

    // 查询备份
    searchBackups() {
      this.currentPage = 1
      this.getBackupList()
    },

    // 重置查询
    resetSearch() {
      this.searchForm = {
        backupName: '',
        backupType: ''
      }
      this.dateRange = []
      this.currentPage = 1
      this.getBackupList()
    },

    // 刷新统计信息
    refreshStatistics() {
      this.getBackupStatistics()
    },

    // 刷新备份列表
    refreshBackupList() {
      this.getBackupList()
    },

    // 刷新最近备份记录
    refreshRecentBackups() {
      this.getRecentBackups()
    },

    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedBackups = selection
    },

    // 下载备份文件
    async downloadBackup(backup) {
      try {
        const res = await downloadBackupFile(backup.id)
        // 创建下载链接
        const blob = new Blob([res])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = backup.backupName + '.sql'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } catch (error) {
        this.$message.error('下载失败：' + (error.message || '未知错误'))
      }
    },

    // 验证备份文件
    async validateBackup(backup) {
      try {
        const res = await validateBackupFile(backup.id)
        if (res.code === 200) {
          const result = res.data
          if (result.valid) {
            this.$message.success(`备份文件有效，大小：${this.formatFileSize(result.fileSize)}`)
          } else {
            this.$message.error('备份文件无效：' + result.message)
          }
        } else {
          this.$message.error(res.message || '验证失败')
        }
      } catch (error) {
        this.$message.error('验证失败：' + (error.message || '未知错误'))
      }
    },

    // 删除备份
    deleteBackup(backup) {
      this.$confirm(`确定要删除备份"${backup.backupName}"吗？此操作不可逆！`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await deleteBackup(backup.id)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getBackupList()
            this.getBackupStatistics()
            this.getRecentBackups()
          } else {
            this.$message.error(res.message || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
        }
      }).catch(() => {
        this.$message.info('已取消删除操作')
      })
    },

    // 批量删除备份
    batchDeleteBackups() {
      if (this.selectedBackups.length === 0) {
        this.$message.warning('请先选择要删除的备份记录')
        return
      }

      this.$confirm(`确定要删除选中的 ${this.selectedBackups.length} 个备份吗？此操作不可逆！`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const backupIds = this.selectedBackups.map(item => item.id)
          const res = await batchDeleteBackups(backupIds)
          if (res.code === 200) {
            this.$message.success('批量删除成功')
            this.getBackupList()
            this.getBackupStatistics()
            this.getRecentBackups()
          } else {
            this.$message.error(res.message || '批量删除失败')
          }
        } catch (error) {
          this.$message.error('批量删除失败：' + (error.message || '未知错误'))
        }
      }).catch(() => {
        this.$message.info('已取消批量删除操作')
      })
    },

    // 分页处理
    handleSizeChange(val) {
      this.pageSize = val
      this.getBackupList()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.getBackupList()
    },

    // 工具方法
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },

    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    // 标签页切换
    handleTabClick(tab) {
      switch (tab.name) {
        case 'schedule':
          this.loadScheduleConfig()
          this.getScheduleTasks()
          break
        case 'logs':
          this.getBackupLogs()
          break
      }
    },

    // 加载自动备份配置
    async loadScheduleConfig() {
      try {
        // 这里应该从后端获取自动备份配置
        // 暂时使用默认值
      } catch (error) {
        console.error('加载自动备份配置失败:', error)
      }
    },

    // 保存自动备份配置
    async handleSaveSchedule() {
      this.$refs.scheduleFormRef.validate(async (valid) => {
        if (valid) {
          this.scheduleSaveLoading = true
          try {
            // 这里应该调用保存自动备份配置的API
            this.$message.success('自动备份配置保存成功')
          } catch (error) {
            console.error('保存自动备份配置失败:', error)
            this.$message.error('保存失败')
          } finally {
            this.scheduleSaveLoading = false
          }
        }
      })
    },

    // 获取最近备份任务
    async getScheduleTasks() {
      this.tasksLoading = true
      try {
        // 这里应该调用获取备份任务的API
        // 暂时使用模拟数据
        this.scheduleTasks = [
          {
            taskName: '每日自动备份',
            executeTime: new Date(),
            backupType: '全量',
            status: '成功',
            duration: '2分15秒',
            fileSize: 15728640,
            errorMessage: ''
          },
          {
            taskName: '每日自动备份',
            executeTime: new Date(Date.now() - 24 * 60 * 60 * 1000),
            backupType: '增量',
            status: '成功',
            duration: '1分30秒',
            fileSize: 5242880,
            errorMessage: ''
          }
        ]
      } catch (error) {
        console.error('获取备份任务失败:', error)
      } finally {
        this.tasksLoading = false
      }
    },

    // 刷新备份任务
    refreshScheduleTasks() {
      this.getScheduleTasks()
    },

    // 获取任务状态类型
    getTaskStatusType(status) {
      switch (status) {
        case '成功':
          return 'success'
        case '失败':
          return 'danger'
        case '进行中':
          return 'warning'
        default:
          return 'info'
      }
    },

    // 获取备份日志
    async getBackupLogs() {
      this.logsLoading = true
      try {
        // 这里应该调用获取备份日志的API
        // 暂时使用模拟数据
        this.backupLogs = [
          {
            id: 1,
            operationType: 'manual_backup',
            description: '手动执行数据库备份',
            operatorName: '管理员',
            operateTime: new Date(),
            status: 'success',
            duration: '2分15秒',
            ipAddress: '192.168.1.100',
            userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
          },
          {
            id: 2,
            operationType: 'auto_backup',
            description: '自动执行数据库备份',
            operatorName: '系统',
            operateTime: new Date(Date.now() - 24 * 60 * 60 * 1000),
            status: 'success',
            duration: '1分30秒',
            ipAddress: '127.0.0.1',
            userAgent: 'System Scheduler'
          }
        ]
        this.logTotal = this.backupLogs.length
      } catch (error) {
        console.error('获取备份日志失败:', error)
      } finally {
        this.logsLoading = false
      }
    },

    // 搜索日志
    searchLogs() {
      this.logCurrentPage = 1
      this.getBackupLogs()
    },

    // 重置日志筛选
    resetLogFilter() {
      this.logFilterForm = {
        operationType: '',
        status: '',
        operator: ''
      }
      this.logDateRange = []
      this.searchLogs()
    },

    // 日志分页处理
    handleLogSizeChange(val) {
      this.logPageSize = val
      this.getBackupLogs()
    },

    handleLogCurrentChange(val) {
      this.logCurrentPage = val
      this.getBackupLogs()
    },

    // 获取操作类型颜色
    getOperationTypeColor(operationType) {
      switch (operationType) {
        case 'manual_backup':
          return 'primary'
        case 'auto_backup':
          return 'success'
        case 'restore':
          return 'warning'
        case 'delete':
          return 'danger'
        default:
          return 'info'
      }
    },

    // 获取操作类型名称
    getOperationTypeName(operationType) {
      switch (operationType) {
        case 'manual_backup':
          return '手动备份'
        case 'auto_backup':
          return '自动备份'
        case 'restore':
          return '数据恢复'
        case 'delete':
          return '文件删除'
        default:
          return '未知操作'
      }
    },

    // 查看日志详情
    viewLogDetail(log) {
      this.$alert(`
        <div><strong>日志ID：</strong>${log.id}</div>
        <div><strong>操作类型：</strong>${this.getOperationTypeName(log.operationType)}</div>
        <div><strong>操作描述：</strong>${log.description}</div>
        <div><strong>操作人：</strong>${log.operatorName}</div>
        <div><strong>操作时间：</strong>${this.formatDateTime(log.operateTime)}</div>
        <div><strong>状态：</strong>${log.status}</div>
        <div><strong>耗时：</strong>${log.duration}</div>
        <div><strong>IP地址：</strong>${log.ipAddress}</div>
        <div><strong>用户代理：</strong>${log.userAgent}</div>
      `, '日志详情', {
        dangerouslyUseHTMLString: true
      })
    },

    // 导出日志
    handleExportLogs() {
      this.$message.success('日志导出功能开发中...')
    },

    // 清空日志
    handleClearLogs() {
      this.$confirm('确定要清空所有备份日志吗？此操作不可逆！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('日志清空成功')
        this.getBackupLogs()
      }).catch(() => {
        this.$message.info('已取消清空操作')
      })
    }
  }
}
</script>

<style scoped>
.backup-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.page-header h2 {
  margin: 0 0 5px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.operation-card {
  min-height: 400px;
}

.card-header {
  display: flex;
  align-items: center;
  color: #409EFF;
}

.card-header i {
  margin-right: 8px;
  font-size: 16px;
}

.restore-actions {
  text-align: center;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.search-form {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.el-table .el-button {
  padding: 7px 15px;
}

.el-table .el-button + .el-button {
  margin-left: 5px;
}

/* 备份标签页样式 */
.backup-tabs {
  margin-bottom: 20px;
}

.schedule-section,
.logs-section {
  margin-top: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.log-filters {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

/* 标签页样式调整 */
.el-tabs__header {
  margin-bottom: 20px;
}

.el-tabs__content {
  padding-top: 0;
}

/* 卡片样式 */
.el-card {
  margin-bottom: 20px;
}

.el-card__header {
  padding: 18px 20px;
  border-bottom: 1px solid #EBEEF5;
}

.el-card__body {
  padding: 20px;
}
</style>